package com.gupao.netty.one.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

// 客户端
public class NettyClient {

public static void main(String[] args) {
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ByteBuf buf = Unpooled.copiedBuffer("&".getBytes());
                    ch.pipeline()
                            .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4))
                            .addLast(new LengthFieldPrepender(4,0,false))

                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(new SimpleClientHander());
                }
            });
    try {
        ChannelFuture channelFuture = bootstrap.connect("localhost",8080).sync();
        channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }finally {
        eventLoopGroup.shutdownGracefully();
    }
}

// int length=12 ===》  00000000 00000000 00000000 00001100 = 12
}
